package br.com.viewcar.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import br.com.viewcar.entity.HistoricoTransmissao;

@Repository
@Transactional
public class HistoricoTransmissaoService extends BaseService<Long, HistoricoTransmissao> {

	@Transactional(readOnly = true)
	public List<HistoricoTransmissao> findByVeiculo(Integer veiculoId, Date dataHoraInicio, Date dataHoraFim) {

		return executeResultListQuery("findByVeiculo", veiculoId, dataHoraInicio, dataHoraFim);
	}

	@Transactional(readOnly = true)
	public List<HistoricoTransmissao> findByVeiculoVelocidade(Integer veiculoId, Date dataInicio, Date dataFim, Float velocidade) {

		return executeResultListQuery("findByVeiculoVelocidade", veiculoId, dataInicio, dataFim, velocidade);
	}

	@Transactional(readOnly = true)
	public Map<Integer, List<HistoricoTransmissao>> findByVeiculoList(List<Integer> veiculoIds, Date dataInicio, Date dataFim) {

		Map<Integer, List<HistoricoTransmissao>> result = new HashMap<Integer, List<HistoricoTransmissao>>();

		for (Integer veiculoId : veiculoIds) {
			result.put(veiculoId, new ArrayList<HistoricoTransmissao>());
		}

		List<HistoricoTransmissao> resultQuery = createVeiculoListQuery(veiculoIds, dataInicio, dataFim);

		for (HistoricoTransmissao historicoTransmissao : resultQuery) {
			result.get(historicoTransmissao.getVeiculoId()).add(historicoTransmissao);
		}

		return result;
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<HistoricoTransmissao> createVeiculoListQuery(List<Integer> veiculoIds, Date dataInicio, Date dataFim) {

		if (veiculoIds != null && veiculoIds.size() > 0) {

			String idsList = veiculoIds.toString().replaceAll("\\[", "(").replaceAll("\\]", ")");
			Query query = entityManager.createQuery("SELECT p FROM HistoricoTransmissao p WHERE p.veiculoId IN " + idsList +
					" AND p.dataTransmissao between ? AND ? AND p.ponto.id > 0 ORDER BY p.dataTransmissao");

			query.setParameter(1, dataInicio);
			query.setParameter(2, dataFim);
			return (List<HistoricoTransmissao>) query.getResultList();

		} else {

			return new ArrayList<HistoricoTransmissao>();
		}
	}
}